/**
 * User: Obi
 * Date: 02.08.11
 * Time: 21:48
 */
package com.jediflasher.game_client.view.world {
	import com.jediflasher.game_client.data.world.CharacterData;
	import com.jediflasher.game_client.events.model.CharacterDataEvent;
	import com.jediflasher.game_client.view.BaseView;

	import flash.display.Graphics;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;

	public class CharacterView extends BaseView {

		public function CharacterView(data:CharacterData) {
			super(data);
			this._characterData = data;
			this._characterData.addEventListener(CharacterDataEvent.NAME_CHANGE, this.updateName);

			super.cacheAsBitmap = true;
		}

		/**
		 * @private
		 */
		private var _characterData:CharacterData;

		/**
		 * @private
		 */
		private var _textField:TextField;

		/**
		 * @inheritDoc
		 */
		override public function render(event:Event = null):Boolean {
			if (!super.render(event)) return false;

			this.draw();

			if (!this._textField) {
				this._textField = new TextField();
				this._textField.autoSize = TextFieldAutoSize.CENTER;
			}

			this.placeTextField();

			if (!super.contains(this._textField)) {
				super.addChild(this._textField);
			}

			return true;
		}

		/**
		 * @inheritDoc
		 */
		override public function clear(event:Event = null):void {
			super.clear(event);
			super.graphics.clear();
			if (this._textField) {
				super.removeChild(this._textField);
			}
		}

		/**
		 * @private
		 */
		private function draw():void {
			var g:Graphics = super.graphics;
			g.clear();
			g.lineStyle(0.1, 0x0);
			g.beginFill(0xFFFFFF, 0.8);
			g.drawCircle(0, 0, 20);
			g.endFill();
		}

		/**
		 * @private
		 */
		private function placeTextField():void {
			this._textField.x = -this._textField.width / 2;
			this._textField.y = -20 - this._textField.height;
		}

		private function updateName(event:Event = null):void {
			var charName:String = this._characterData.name ? this._characterData.name : "";
			this._textField.text = this._characterData.name + " (" + this._characterData.id + ")";
			this.placeTextField();
		}
	}
}
